/**
 * Program   :   ClasspathListResourceBundle.java
 * Author    :   shadow guo
 * Create    :   2013-6-4 上午9:10:19
 *
 * Copyright 2008 by Tongfu Information Technology Co. Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Tongfu Information Technology Co. Ltd. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tongfu Information Technology Co. Ltd.
 * 
 */
package com.tongfusoft.web.core.service.impl.list;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tongfusoft.web.core.exception.ResourceException;

public class ClasspathListResourceBundle implements ListResourceBundle{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(ClasspathListResourceBundle.class);
	
	private List<ListResource> resources = new ArrayList<ListResource>();
	private static Map<String,ListResourceElement> listRes = null;//new HashMap<String,ListResourceElement>();
	private ListYAMLParser parser = new ListYAMLParser();
	
	@SuppressWarnings("unchecked")
	@Override
	public List<ListResource> getListResources() {
		try {
//			logger.debug(this.getClass().getClassLoader().getResource(""));
			Enumeration<URL> systemResources = ClassLoader
					.getSystemResources("");
			List<URL> urls = new ArrayList<URL>();
			while (systemResources.hasMoreElements()) {
				urls.add(systemResources.nextElement());
			}
			
			if(urls.size() == 0){
				urls.add(this.getClass().getClassLoader().getResource(""));
			}
			
			for(URL url : urls){
				logger.debug(url.getPath());
				File file = new File(url.getPath());
				discoverResources(file, file);
			}
		} catch (IOException e) {
			
		}
		
		return resources;
	}
	
	private void discoverResources(File root, File folder) {
		if (folder.listFiles() != null)
			for (File file : folder.listFiles()) {
				if (file.isDirectory())
					discoverResources(root, file);
				else
					addResource(root, file);
			}
	}
	
	private void addResource(File root, File file) {
		logger.debug(file.getAbsolutePath());
		
		if (file.getName().equals("list.yaml")) {
			System.out.println("AAAAAAAAAAAAAAAAAA:"+file.getPath()+"--"+file.getName());
			String uri = resolvePath(root, file.getParentFile());
			ListResource lrs = new ListResource(uri,uri);
			resources.add(lrs);
		}
	}
	
	private String resolvePath(File root, File file) {
		URI uri = root.toURI();
		URI uri2 = file.toURI();
		return uri.relativize(uri2).getPath();
	}
	
	public static void main(String[] args) {
		ListResourceBundle test = new ClasspathListResourceBundle();
		test.getListResources();
		test.parserElement();
	}
	
	
	public void parserElement(){
		if(listRes == null){
			listRes = new HashMap<String,ListResourceElement>();
		}
		logger.info(resources + "c:======================================================");
		if(resources != null && resources.size() > 0){
			for(ListResource res : resources){
				logger.info("yamlURI:"+res.getUri());
				listRes = parser.parser(res.getUri(), listRes);
				logger.info(listRes+"ff:====================================================");
			}
		}
		logger.info(listRes+"a:====================================================");
	}

	@Override
	public ListResourceElement getListElement(String name) {
		if(listRes == null){
			parserElement();
		}
		
		if(listRes.containsKey(name)){
			return listRes.get(name);
		}else{
			Map map =  listRes;
			Iterator it = map.entrySet().iterator();
			logger.info(listRes.size()+"d:====================================================");
			logger.info("ymalKey:");
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				logger.info("ymalKey:"+entry.getKey());
			} 
			
			System.out.println("BBBBBBBBBBBBBBBBBBBB:"+name);
			throw new ResourceException("not find resource " + name);
		}
	}

}
